const {chromium} = require('playwright');

const proxy_obj = {
  server: 'http://u5329.b5.t.16yun.cn:6460',
  username: '16GADNHJ',
  password: '936441'
};

(async () => {
  const browser = await chromium.launch({headless: false});
  let page = await browser.newPage({proxy: proxy_obj});
  await page.goto('https://tophub.today/n/74KvxwokxM/', {waitUntil: 'domcontentloaded', timeout: 10000});

  await page.waitForSelector('div:nth-child(2) > div > div > div > table > tbody > tr', {timeout: 10000});
  let eles = await page.$$('div:nth-child(2) > div > div > div > table > tbody > tr');
  let cnts = eles.length;

  console.log(cnts);


  for (let i = 0; i < cnts; i++) {
    let newPage;
    try {
      let topic = {};
      let idx = `#page > div > div > div:nth-child(2) > div > div > div > table > tbody > tr:nth-child(${i + 1}) > td.al > a`;
      await page.waitForSelector(`div:nth-child(2) > div > div > div > table > tbody > tr`, {
        timeout: 10000,
        state: 'attached'
      });

      topic.title = await page.$eval(idx, el => el.innerText);
      topic.content = await page.$eval(idx, el => el.href);

      let context = browser.contexts()[0];

      [newPage] = await Promise.all([
        context.waitForEvent('page', {timeout: 10000}),
        page.click(idx),
      ]);

      topic.content = newPage.url();

      console.log(i, cnts, topic);
      newPage.close();
    } catch (e) {
      console.error(e.message);
    } finally {
      if (newPage) {
        newPage.close();
      }
    }
  }

})();
